package com.zzf.concurrent.example.design.pattern.single.thread;

import lombok.extern.slf4j.Slf4j;

/**
 * 检票的门
 * @author GaoFeng2017
 * @date 2019/9/6 15:28
 */
@Slf4j
public class Gate {
    private int count = 0;
    private String idCard;
    private String ticket;

    /**
     * 检查票据是否正确，此处会并发访问同步资源，通过添加synchronized关键字来保证只有单个线程去访问临界资源
     * @author ZengZhengFang
     * @date 2019/9/6 16:05
     * @param idCard
     * @param ticket
     * @return void
     */
    public synchronized void pass(String idCard, String ticket) {
        this.count++;
        this.idCard = idCard;
        this.ticket = ticket;
        this.check();
    }

    private void check() {
        if (this.idCard.charAt(0) != this.ticket.charAt(0)) {
            log.info("******INVALID TICKET******, {}", toString());
        }
    }

    @Override
    public synchronized String toString() {
        return "NO." + count + ", idCard: " + idCard + ", ticket: "+ ticket;
    }
}
